package skipClass.java;

import skipClass.java.ExamQuestion;
import skipClass.java.ExamQuestionReader;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class QuestionListActivity extends Activity
{
	private final static String TAG = "ClassSkippers";
	private TextView QuestionTV;
	private TextView ExcuseTV;
	private TextView ScoreTV;
	private TextView MaxScoreTV;
	private ListView QuestionLV;
	private ArrayList<ExamQuestion> Questions;
	private ExamQuestionAdapter QuestionAdapter;
	
	private int NumAttempted;
	private int NumWrong;
	private int NumExcused;
	
	private static final int MAX_NUM_EXCUSED = 2;
	
	private static final String DEFAULT_EXCUSE_MESSAGE = "Number of excuses left: ";
	
	private static final String DEFAULT_SCORE_MESSAGE = "Current score: ";
	
	private static final String DEFAULT_MAX_SCORE_MESSAGE = "Maximum score achievable: ";
	
	public static final double FAIL_THRES = 70.0f;
	
	Typeface font;
	
	private ArrayList<String> AvailableExcuses;
	
	private static final int DEFAULT_LIST_LAYOUT = R.layout.question_list_item;
	private static final int DEFAULT_LIST_TV = R.id.question_list_item_tv;
	private static final int DEFAULT_LIST_IV = R.id.question_list_item_iv;
	private static final int DEFAULT_EMPTY_LIST_LAYOUT = R.layout.question_list_empty;
	private static final int DEFAULT_LIST_WRONG = R.drawable.wrong;
	private static final int DEFAULT_LIST_RIGHT = R.drawable.right;
	private static final int DEFAULT_LIST_NO_ATTEMPTS = R.drawable.no_attempts;
	private static final int DEFAULT_LIST_EXCUSED = R.drawable.excused;
	
	private static final int ASK_QUESTION_REQUEST_CODE = 0;
	
	private class ExamQuestionAdapter extends ArrayAdapter<ExamQuestion>
	{	
		ArrayList<ExamQuestion> Questions;
		int _textViewResourceId = -1;
		int _resource = -1;
		
		public ExamQuestionAdapter(Context context, int textViewResourceId, ExamQuestion[] objects)
		{
			super(context, textViewResourceId, objects);
			
			_textViewResourceId = textViewResourceId;
			
			Questions = new ArrayList<ExamQuestion>(objects.length);
			
			for (int i = 0; i < objects.length; i++)
			{
				Questions.add(objects[i]);
			}
			
		}

		public ExamQuestionAdapter(Context context, int resource, int textViewResourceId, ExamQuestion[] objects)
		{
			super(context, resource, textViewResourceId, objects);
			
			_resource = resource;
			_textViewResourceId = textViewResourceId;
			
			Questions = new ArrayList<ExamQuestion>(objects.length);
			
			for (int i = 0; i < objects.length; i++)
			{
				Questions.add(objects[i]);
			}
			
		}

		public ExamQuestionAdapter(Context context, int resource, int textViewResourceId, List<ExamQuestion> objects)
		{
			super(context, resource, textViewResourceId, objects);
			
			_resource = resource;
			_textViewResourceId = textViewResourceId;
			
			Questions = new ArrayList<ExamQuestion>(objects);
		}

		public ExamQuestionAdapter(Context context, int resource, int textViewResourceId)
		{
			super(context, resource, textViewResourceId);
			
			_resource = resource;
			_textViewResourceId = textViewResourceId;
			
			Questions = new ArrayList<ExamQuestion>();
		}

		public ExamQuestionAdapter(Context context, int textViewResourceId, List<ExamQuestion> objects)
		{
			super(context, textViewResourceId, objects);
			
			_textViewResourceId = textViewResourceId;
			
			Questions = new ArrayList<ExamQuestion>(objects);
		}

		public ExamQuestionAdapter(Context context, int textViewResourceId)
		{
			super(context, textViewResourceId);
			
			_textViewResourceId = textViewResourceId;
			
			Questions = new ArrayList<ExamQuestion>();
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null)
			{
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(QuestionListActivity.this.DEFAULT_LIST_LAYOUT, null);
			}
			
			if (Questions.isEmpty())
			{
				View ev;
				
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                ev = vi.inflate(QuestionListActivity.this.DEFAULT_EMPTY_LIST_LAYOUT, null);
                return ev;
			}
			
			ExamQuestion question = Questions.get(position);
			
			ImageView iv = (ImageView) v.findViewById(QuestionListActivity.this.DEFAULT_LIST_IV);
			TextView tv = (TextView) v.findViewById(QuestionListActivity.this.DEFAULT_LIST_TV);
			
			if (question != null)
			{	
				tv.setText(question.getQuestion());
				tv.setTypeface(QuestionListActivity.this.font); 
				
				switch(question.getAnsweredStatus())
				{
					case ExamQuestion.NOT_ATTEMPTED:
						iv.setImageResource(QuestionListActivity.this.DEFAULT_LIST_NO_ATTEMPTS);
						break;
					case ExamQuestion.WRONG:
						iv.setImageResource(QuestionListActivity.this.DEFAULT_LIST_WRONG);
						break;
					case ExamQuestion.CORRECT:
						iv.setImageResource(QuestionListActivity.this.DEFAULT_LIST_RIGHT);
						break;
					case ExamQuestion.EXCUSED:
						iv.setImageResource(QuestionListActivity.this.DEFAULT_LIST_EXCUSED);
						break;
				}
			}
			
			else
			{
				tv.setText("Invalid question!");
				tv.setTypeface(QuestionListActivity.this.font);
				iv.setImageResource(QuestionListActivity.this.DEFAULT_LIST_WRONG);
			}
			
			return v;
		}
		
		@Override
		public int getCount()
		{
			return Questions.size();
		}
		
		@Override
		public void add(ExamQuestion object)
		{
			Questions.add(object);
		}
		
		public void addAll (ArrayList<ExamQuestion> collection)
		{
			Questions.addAll(collection);
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.question_list);
		
		NumAttempted = 0;
		
		NumWrong = 0;
		
		font = Typeface.createFromAsset(getAssets(), "font/GoodDog.otf");
		
		QuestionTV = (TextView) findViewById(R.id.question_list_tv);
		
		QuestionTV.setTypeface(font);
		
		ExcuseTV = (TextView) findViewById(R.id.question_list_excuses_tv);
		
		ExcuseTV.setTypeface(font);
		ExcuseTV.setText(DEFAULT_EXCUSE_MESSAGE + MAX_NUM_EXCUSED);
		
		ScoreTV = (TextView) findViewById(R.id.question_list_score_tv);
		
		ScoreTV.setTypeface(font);
		ScoreTV.setText(DEFAULT_SCORE_MESSAGE + "0%");
		
		MaxScoreTV = (TextView) findViewById(R.id.question_list_max_score_tv);
		
		MaxScoreTV.setTypeface(font);
		MaxScoreTV.setText(DEFAULT_MAX_SCORE_MESSAGE + "100%");
		
		QuestionLV = (ListView) findViewById(R.id.question_list_lv);
		
		if (QuestionLV == null)
		{
			Log.e(TAG, "Could not find ListView");
			finish();
		}
		
		
		QuestionLV.setOnItemClickListener(
				new OnItemClickListener() 
				{
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) 
					{	
						ExamQuestion question = Questions.get(position);
						
						if (question.getAnsweredStatus() == ExamQuestion.NOT_ATTEMPTED)
						{
							Intent intent = new Intent(QuestionListActivity.this, QuestionAskActivity.class);
						
							intent.putExtra("QuestionPos", position);
							intent.putExtra("Question", question.getQuestion());
							intent.putExtra("Answer", question.getRealAnswer());
							intent.putStringArrayListExtra("BogusAnswers", question.getBogusAnswers());
							
							if (NumExcused < MAX_NUM_EXCUSED)
							{
								intent.putExtra("CanExcuse", true);
							}
							
							else
							{
								intent.putExtra("CanExcuse", false);
							}
							
							intent.putStringArrayListExtra("Excuses", AvailableExcuses);
						
							startActivityForResult(intent, QuestionListActivity.ASK_QUESTION_REQUEST_CODE);
						}
					}
				}
			);
		
		
		AvailableExcuses = new ArrayList<String>();
		
		String[] excuses = getResources().getStringArray(R.array.excuses);
		
		for (int i = 0; i < excuses.length; i++)
		{
			AvailableExcuses.add(excuses[i]);
		}
		
		ExamQuestionReader qReader = new ExamQuestionReader(this, R.raw.questions);
		
		Questions = qReader.readXmlFile();
		
		if (Questions != null)
		{
			Log.i(TAG, Questions.size() + " questions read.");
			
			QuestionAdapter = new ExamQuestionAdapter(this, R.layout.question_list_item, R.id.question_list_item_tv);
			
			QuestionLV.setAdapter(QuestionAdapter);
			
			Collections.shuffle(Questions);
			
			QuestionAdapter.addAll(Questions);
			
			QuestionAdapter.notifyDataSetChanged();
		}
		
		else
		{
			Log.w(TAG, "Could not get questions from XML file");
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent)
	{
		super.onActivityResult(requestCode, resultCode, intent);
		
		switch(requestCode)
		{
			case ASK_QUESTION_REQUEST_CODE:
			{
				if (intent != null)
				{
					Bundle extras = intent.getExtras();
					int position = extras.getInt("QuestionPos");
					int status = extras.getInt("AnswerStatus");
				
					switch(status)
					{
						case ExamQuestion.NOT_ATTEMPTED:
							break;
						case ExamQuestion.WRONG:
							NumWrong++;
						case ExamQuestion.CORRECT:
							NumAttempted++;
							
							ScoreTV.setText(DEFAULT_SCORE_MESSAGE + ((((double)(NumAttempted - NumWrong))/Questions.size()) * 100) + "%");
							
							MaxScoreTV.setText(DEFAULT_MAX_SCORE_MESSAGE + ((((double)(Questions.size() - NumWrong))/Questions.size()) * 100) + "%");
							
							Questions.get(position).setAnsweredStatus(status);
							break;
						case ExamQuestion.EXCUSED:
							NumAttempted++;
							NumExcused++;
							
							ExcuseTV.setText(DEFAULT_EXCUSE_MESSAGE + (MAX_NUM_EXCUSED - NumExcused));
							
							ScoreTV.setText(DEFAULT_SCORE_MESSAGE + ((((double)(NumAttempted - NumWrong))/Questions.size()) * 100) + "%");
							
							MaxScoreTV.setText(DEFAULT_MAX_SCORE_MESSAGE + ((((double)(Questions.size() - NumWrong))/Questions.size()) * 100) + "%");
							
							Questions.get(position).setAnsweredStatus(status);
							
							int excuse_pos = extras.getInt("ExcusePos");
							
							AvailableExcuses.remove(excuse_pos);
							break;
					}
				
					QuestionAdapter.notifyDataSetChanged();
					
					if (NumAttempted == Questions.size())
					{
						if (((((double)(NumAttempted - NumWrong))/Questions.size()) * 100) < FAIL_THRES)
						{
							Intent newIntent = new Intent(QuestionListActivity.this, FailActivity.class);
							startActivity(newIntent);
							finish();
						}
						
						else
						{
							Intent newIntent = new Intent(QuestionListActivity.this, PassActivity.class);
							startActivity(newIntent);
							finish();						
						}
					}
				}
				break;
			}
		}
    }

}
